package com.wudl.file.service.impl;

import com.wudl.common.api.CommonResult;
import com.wudl.common.api.ResultCode;
import com.wudl.file.domain.FileInfo;
import com.wudl.file.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：wudl
 * @date ：Created in 2022-03-17 18:45
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;


    @Override
    public CommonResult createBucket(String bucket) {
        boolean found = false;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        } catch (Exception e) {
            log.info("创建bucket 失败----------------{}", e.getMessage());
            e.printStackTrace();
            return CommonResult.failed(ResultCode.FAILED);
        }
        if (!found) {
            try {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
            } catch (Exception e) {
                log.info("创建bucket 失败----------------{}", e.getMessage());
                e.printStackTrace();
                return CommonResult.failed(ResultCode.FAILED);
            }
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    @Override
    public CommonResult uploadFile(InputStream stream, String bucket, String objectName) {
        try {
            minioClient.putObject(PutObjectArgs.builder().bucket(bucket).object(objectName)
                    .stream(stream, -1, 10485760).build());
        } catch (Exception e) {
            log.info("文件上传失败------------->{}", e.getMessage());
            e.printStackTrace();
            CommonResult.failed(ResultCode.FAILED);
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    public void uploadfileMultipar(InputStream stream, String bucket, String objectName) throws Exception {
        minioClient.putObject(PutObjectArgs.builder().bucket(bucket).object(objectName)
                .stream(stream, -1, 10485760).build());
    }

    @Override
    public CommonResult<List<String>> listBuckets() {

        List<Bucket> list = null;
        try {
            list = minioClient.listBuckets();
        } catch (Exception e) {
            log.info("列出所有的桶失败------------->{}", e.getMessage());
            e.printStackTrace();
            CommonResult.failed(ResultCode.FAILED);
        }
        List<String> names = new ArrayList<>();
        list.forEach(b -> {
            names.add(b.name());
        });
        return CommonResult.success(names);
    }

    @Override
    public CommonResult<List<FileInfo>> listFiles(String bucket) {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucket).recursive(true).build());

        List<FileInfo> infos = new ArrayList<>();
        results.forEach(r->{
            FileInfo info = new FileInfo();
            try {
                Item item = r.get();
                info.setFilename(item.objectName());
                info.setDirectory(item.isDir());
                infos.add(info);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return CommonResult.success(infos);
    }

    @Override
    public CommonResult<InputStream> download(String bucket, String objectName) {
        InputStream stream = null;
        try {
            stream = minioClient.getObject(
                    GetObjectArgs.builder().bucket(bucket).object(objectName).build());
        } catch (Exception e) {
            log.info("下载失败------------->{}", e.getMessage());
            e.printStackTrace();
            CommonResult.failed(ResultCode.FAILED);
        }
        return    CommonResult.success(stream);
    }


    /**
     * 下载一个文件
     */
    @Override
    public InputStream downloadFile(String bucket, String objectName) throws Exception {
        InputStream stream = minioClient.getObject(
                GetObjectArgs.builder().bucket(bucket).object(objectName).build());
        return stream;
    }


    @Override
    public CommonResult deleteBucket(String bucket) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucket).build());
        } catch (Exception e) {
            log.info("删除桶失败------------->{}", e.getMessage());
            e.printStackTrace();
            CommonResult.failed(ResultCode.FAILED);

        }
        return CommonResult.success(ResultCode.SUCCESS);

    }

    @Override
    public CommonResult deleteObject(String bucket, String objectName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(objectName).build());
        } catch (Exception e) {
            log.info("删除桶失败------------->{}", e.getMessage());
            e.printStackTrace();
            CommonResult.failed(ResultCode.FAILED);
        }

        return CommonResult.success(ResultCode.SUCCESS);
    }
}
